<template>
  <div v-if="!forceUpdate" class="richtext-container">
    <div style="width:100%" class="el-table el-table--fit el-table--border">
      <div class="el-table__body-wrapper">
        <table cellspacing="0" cellpadding="0" border="0" style="width:100%" class="el-table__body">
          <tbody>
            <tr>
              <td style="padding:0px;">
                <textarea :id="id" :style="'height:'+height+'px'" class="richtext" />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
    name: 'RichtextEditor',
    props: {
        value: { type: String, default: '' },
        height: { type: Number, default: 260 },
        toolbar: { type: String, default: 'standard' },
        startupMode: { type: String, default: 'wysiwyg' },
        imageUploadUrl: { type: String, default: null },
        imageBrowseUrl: { type: String, default: null },
        videoBrowseUrl: { type: String, default: null },
        canEdit: { type: Number, default: null }
    },
    data: function() {
        return {
            id: parseInt(Math.random() * 10000).toString(),
            ckeditor: null,
            toolbarBtns: [],
            uploadUrl: '',
            forceUpdate: false
        }
    },
    watch: {
        value: function() {
            // 监听prop的变化，更新ckeditor中的值
            if (this.value !== this.ckeditor.getData()) {
                this.ckeditor.setData(this.value)
            }
        },
        canEdit: function() {
            let readOnly = false
            if (this.canEdit === 0 || this.canEdit === '0') {
                readOnly = true
            }
            this.ckeditor.destroy()
            this.initCkeditorToolbar(readOnly)

            const timer = window.setInterval(() => {
                const ifrm = document.querySelector('.cke_wysiwyg_frame')
                if (ifrm !== undefined && ifrm.contentDocument.body) {
                    window.clearInterval(timer)
                    ifrm.contentDocument.body.style.margin = '5px'
                    if (readOnly) {
                        document.querySelector('.cke_contents').style.height = (ifrm.contentDocument.body.clientHeight + 90) + 'px'

                        document.querySelector('.cke_top').style.display = 'none'
                    }

                    if (document.querySelector('.cke_browser_webkit')) {
                        document.querySelector('.cke_browser_webkit').style.border = 0
                    }
                }
            }, 10)
        }
    },
    mounted: function() {
        let toolbarBtns = [
            ['Maximize'],
            // 加粗     斜体，     下划线
            ['Bold', 'Italic', 'Underline'],
            // 左对 齐             居中对齐          右对齐          两端对齐
            ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
            // 样式       格式      字体    字体大小
            ['Styles', 'Format', 'Font', 'FontSize', 'lineheight'],
            // 文本颜色     背景颜色
            ['TextColor', 'BGColor'],
            ['Image', 'Html5video', 'Table']
        ]
        if (this.toolbar === 'multimedia') {
            toolbarBtns = [
                ['Maximize'],
                ['Styles', 'Format', 'Font', 'FontSize', 'lineheight'],
                ['Undo', 'Redo', '-', 'basicstyles', 'cleanup'],
                ['Replace'],
                ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'],
                ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat'],
                ['TextColor', 'BGColor'],
                ['Link', 'Unlink'],
                ['Image', 'Html5video', 'Html5audio', 'Table', 'SpecialChar']
            ]
        }
        if (this.toolbar === 'mini') {
            toolbarBtns = [
                ['Maximize'],
                // 加粗     斜体，     下划线
                ['Bold', 'Italic', 'Underline'],
                // 左对 齐             居中对齐          右对齐
                ['JustifyLeft', 'JustifyCenter', 'JustifyRight'],
                // 格式      字体    字体大小
                ['Format', 'Font', 'FontSize'],
                // 文本颜色     背景颜色
                ['TextColor', 'BGColor']
            ]
        }
        if (this.toolbar === 'full') {
            toolbarBtns = [
                ['Maximize'],
                ['Styles', 'Format', 'Font', 'FontSize', 'lineheight'],
                ['Undo', 'Redo', '-', 'basicstyles', 'cleanup'],
                ['Replace'],
                ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'],
                ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat'],
                ['TextColor', 'BGColor'],
                ['Link', 'Unlink'],
                ['Image', 'Multiimg', 'Html5video', 'Html5audio', 'Table', 'SpecialChar']
            ]
        }
        this.toolbarBtns = toolbarBtns

        let readOnly = false
        let formCanEdit = this.$vnode.context.canEdit
        if (this.$vnode.context.curTN) formCanEdit = this.$vnode.context.curTN.tnCanEdit
        if (this.canEdit !== null) formCanEdit = this.canEdit
        if (formCanEdit === 0 || formCanEdit === '0') {
            readOnly = true
        }

        let uploadUrl = this.imageUploadUrl
        if (uploadUrl == null && this.$vnode.context.wfInstance) {
            if (this.$vnode.context.wfEngineUrl) {
                uploadUrl = process.env.VUE_APP_BASE_API + '/' + this.$vnode.context.wfEngineUrl + '/uploadBodyPicture?module=' + this.$vnode.context.wfInstance.module + '&busiDataId=' + this.$vnode.context.wfInstance.busiDataId + '&attachsType=BODY&apigw=' + process.env.VUE_APP_BASE_API
            } else {
                uploadUrl = process.env.VUE_APP_BASE_API + '/workflow/wfBusiAttach/uploadBodyPicture?module=' + this.$vnode.context.wfInstance.module + '&busiDataId=' + this.$vnode.context.wfInstance.busiDataId + '&attachsType=BODY&apigw=' + process.env.VUE_APP_BASE_API
            }
        }
        if (uploadUrl.indexOf('?') !== -1) {
            uploadUrl += '&httpPort=' + location.port
        } else {
            uploadUrl += '?httpPort=' + location.port
        }
        this.uploadUrl = uploadUrl
        this.initCkeditorToolbar(readOnly)

        if (this.imageBrowseUrl !== null) {
            if (this.imageBrowseUrl.indexOf('?') !== -1) {
                this.imageBrowseUrl += '&httpPort=' + location.port
            } else {
                this.imageBrowseUrl += '?httpPort=' + location.port
            }
        }
        if (this.videoBrowseUrl !== null) {
            if (this.videoBrowseUrl.indexOf('?') !== -1) {
                this.videoBrowseUrl += '&httpPort=' + location.port
            } else {
                this.videoBrowseUrl += '?httpPort=' + location.port
            }
        }

        // 上传对话框，给文件选择按钮设置accept属性
        this.ckeditor.on('dialogShow', function(evt) {
            const uploadTab = evt.data.getContentElement('Upload', 'upload')
            if (uploadTab != null) {
                const ifrm = uploadTab.getElement().find('IFRAME')
                if (ifrm.$.length > 0) {
                    const fileInput = $(ifrm.$[0]).contents().find('body').find("INPUT[type='file']")
                    if (fileInput.length > 0) {
                        fileInput.prop('accept', evt.data.getContentElement('Upload', 'upload').accept)
                    }
                }
            }
        })

        this.ckeditor.on('fileUploadRequest', function(evt) {
            console.log('fileUploadRequest 开始上传...')
            const fileLoader = evt.data.fileLoader
            const reqData = evt.data.requestData

            // 按ecinc开发框架规范，将附件变量名改为file
            reqData.file = reqData.upload
            delete reqData.upload
            // 允许跨域请求
            fileLoader.crossDomain = true
            fileLoader.xhr.withCredentials = true
        })

        this.ckeditor.on('fileUploadResponse', () => {
            console.log('fileUploadResponse 上传结束.')
            const ifrm = document.querySelector('.cke_wysiwyg_frame')
            if (ifrm) {
                const content = this.ckeditor.getData().replace(/<span style="background: url.*?>.*?<\/span>/g, '')
                this.$emit('input', content)
            }
        })

        this.ckeditor.on('instanceReady', () => {
            console.log('instanceReady setData...')

            // 设置初始内容
            this.ckeditor.setData(this.value)

            const ifrm = document.querySelector('.cke_wysiwyg_frame')
            if (ifrm) {
                ifrm.contentDocument.body.style.margin = '5px'
            }

            if (this.startupMode !== 'source') {
                this.ckeditor.config.filebrowserImageUploadUrl = uploadUrl // 上传图片的地址
                this.ckeditor.config.filebrowserImageBrowseUrl = this.imageBrowseUrl // 浏览图片的地址
                this.ckeditor.config.uploadUrl = this.uploadUrl + '&paste=true' // 剪贴版粘贴上传图片的地址
                this.ckeditor.config.filebrowserHtml5videoUploadUrl = uploadUrl // 上传视频的地址
                this.ckeditor.config.filebrowserHtml5videoBrowseUrl = this.videoBrowseUrl // 浏览视频的地址
                this.ckeditor.config.filebrowserHtml5audioUploadUrl = uploadUrl // 上传音频的地址
                this.ckeditor.config.filebrowserUploadUrl = this.uploadUrl // 上传附件的地址

                if (readOnly) {
                    const ifrm = document.querySelector('.cke_wysiwyg_frame')
                    document.querySelector('.cke_contents').style.height = (ifrm.contentDocument.body.clientHeight + 90) + 'px'

                    document.querySelector('.cke_top').style.display = 'none'
                }
                if (document.querySelector('.cke_browser_webkit')) {
                    document.querySelector('.cke_browser_webkit').style.border = 0
                }
            }
        })

        // 监听内容变更事件
        this.ckeditor.on('change', () => {
            const content = this.ckeditor.getData().replace(/<span style="background: url.*?>.*?<\/span>/g, '')
            this.$emit('input', content)
        })
        this.ckeditor.on('blur', () => {
            const content = this.ckeditor.getData().replace(/<span style="background: url.*?>.*?<\/span>/g, '')
            this.$emit('input', content)
        })
        this.ckeditor.on('key', (evt) => {
            if (this.startupMode !== 'source') {
                // wysiwyg mode,将nbsp转为ensp、将tab转为4个ensp
                if (evt.data.keyCode === 32) {
                    this.ckeditor.insertHtml('&ensp;')
                    evt.cancel()
                } else if (evt.data.keyCode === 9) {
                    this.ckeditor.insertHtml('&ensp;&ensp;&ensp;&ensp;')
                    evt.cancel()
                }
            }
        })
    },
    beforeDestroy: function() {
        this.ckeditor.destroy()
    },
    methods: {
        initCkeditorToolbar(readOnly) {
            if (this.startupMode === 'source') {
                const richtext = document.querySelector('.richtext')
                const cssHeight = richtext.style.height
                if (cssHeight === undefined || parseInt(cssHeight) < 300) {
                    this.height = 300
                }

                const toolbarBtns = [['Maximize']]
                this.ckeditor = window.CKEDITOR.replace(this.id, {
                    toolbar: toolbarBtns,
                    height: this.height + 'px',
                    allowedContent: true,
                    startupMode: 'source',
                    readOnly: readOnly
                })
            } else {
                this.ckeditor = window.CKEDITOR.replace(this.id, {
                    toolbar: this.toolbarBtns,
                    height: this.height + 'px',
                    allowedContent: true,
                    filebrowserImageUploadUrl: this.uploadUrl, // 上传图片的地址
                    filebrowserImageBrowseUrl: this.imageBrowseUrl, // 浏览图片的地址
                    uploadUrl: this.uploadUrl + '&paste=true', // 剪贴版粘贴上传图片的地址
                    filebrowserHtml5videoUploadUrl: this.uploadUrl, // 上传视频的地址
                    filebrowserHtml5videoBrowseUrl: this.videoBrowseUrl, // 浏览视频的地址
                    filebrowserHtml5audioUploadUrl: this.uploadUrl, // 上传音频的地址
                    filebrowserUploadUrl: this.uploadUrl, // 上传附件的地址
                    readOnly: readOnly
                })
            }
        }
    }
}
</script>

<style scoped lang="scss">
.richtext-container{
    margin:20px 0 0 0;
}
</style>
